// facility/mapScreen/mapScreen.js
import http from '../../http'
import Toast from '@vant/weapp/toast/toast';
let toast;
let num = 0
let timer;
Component({
	options: {
		styleIsolation: 'shared'
	},
	/**
	 * 组件的属性列表
	 */
	properties: {
		infoType: '',
		nowProjectInfo: '',
		nowfacilityInfo: '',
	},

	/**
	 * 组件的初始数据
	 */
	data: {
		// 表单参数
		form: {
			command: undefined, //命令标识
			factoryParams: [],
			order: {} //命令内容
		},
		//下发节目
		programBol: false,
		programList: [],
		// 屏幕控制
		btsType: '1',
		screenControlBol: false,
		screenBts: 0,
		sensitivity: '',
		minBrightness: '',
		// 截屏
		screenCaptureBol: false,
		screenFile: [],

		// 下发结果
		issueResultBol: false,
		issueResult: [],
	},

	/**
	 * 组件的方法列表
	 */
	methods: {
		start(value) {
			wx.showLoading({
				title: '加载中...'
			});
			// 组控
			if (this.properties.infoType == 'project') {
				let data = {
					pageNo: 1,
					pageSize: -1,
					categoryId: "screen",
				}
				if (this.properties.nowProjectInfo.type == 0) {
					data.projectId = this.properties.nowProjectInfo.id
				} else {
					data.group = this.properties.nowProjectInfo.id
				}
				http.get({
					url: '/zg/device-instance/page',
					data: data,
					then: (res) => {
						console.log('显示屏列表', res);
						let form = this.data.form
						form.factoryParams = res.data.data.list.map(item => {
							return {
								productId: item.productId,
								sn: item.sn
							}
						})
						this.setData({
							form: form,
						}, () => {
							if (this.data.form.factoryParams.length == 0) {
								wx.showToast({
									title: '该项目下没有显示屏',
									icon: 'error',
								})
							} else {
								wx.hideLoading()
								if (value == 'program') {
									this.setData({
										programBol: true
									})
								} else if (value == 'screenControl') {
									this.setData({
										screenControlBol: true
									})
								} else if (value == 'subTitle') {
									wx.navigateTo({
										url: `../editor/editor?form=${JSON.stringify(this.data.form)}`,
									})
								} else if (value == 'screenCapture') {
									this.setData({
										screenCaptureBol: true
									})
									this.websocketLink()
								}
							}
						});
					}
				})
			} else {
				// 单控
				http.get({
					url: '/zg/device-instance/get',
					data: {
						id: this.properties.nowfacilityInfo.id
					},
					then: (res) => {
						console.log('显示屏信息', res);
						let data = {
							productId: res.data.data.productId,
							sn: res.data.data.sn
						}
						let form = this.data.form
						form.factoryParams = [data]
						this.setData({
							form: form,
						}, () => {
							wx.hideLoading()
							if (value == 'program') {
								this.setData({
									programBol: true
								})
							} else if (value == 'screenControl') {
								this.setData({
									screenControlBol: true
								})
							} else if (value == 'subTitle') {
								wx.navigateTo({
									url: `../editor/editor?form=${JSON.stringify(this.data.form)}`,
								})
							} else if (value == 'screenCapture') {
								this.setData({
									screenCaptureBol: true
								})
								this.websocketLink()
							}
						});
					}
				})
			}
		},
		// websocket
		websocketLink() {
			toast = Toast.loading({
				duration: 0, // 持续展示 toast
				forbidClick: true,
				message: '请稍后(0/' + this.data.form.factoryParams.length + ')',
			});
			wx.connectSocket({
				url: http.screen + '/ws/screen/screenshot/shot',
				success: function () {
					console.log('WebSocket连接成功！')
				}
			})
			wx.onSocketOpen((res) => {
				console.log('WebSocket连接已打开！')
				console.log('参数', this.data.form);
				// 请求超时
				timer = setTimeout(() => {
					Toast.fail('请求超时')
					num = 0
					this.setData({
						issueResultBol: true,
						form: {
							command: undefined, //命令标识
							factoryParams: this.data.form.factoryParams,
							order: {} //命令内容 
						},
					})
					this.websocketClose()
				}, 7000);

				// 发送消息
				wx.sendSocketMessage({
					data: JSON.stringify(this.data.form)
				})
			})
			wx.onSocketMessage((res) => {
				console.log('收到服务器消息：', JSON.parse(res.data))
				let news = JSON.parse(res.data)
				// 判断是截屏图片还是下发结果
				if (news.status) {
					num++
					let list = this.data.issueResult
					list = [...list, {
						name: news.sn,
						status: news.status
					}]
					this.setData({
						issueResult: list
					})
				} else {
					let list = this.data.screenFile
					list = [...list, {
						name: news.sn,
						url: news.data
					}]
					this.setData({
						screenFile: list
					})
				}

				console.log(num, this.data.form.factoryParams.length);
				if (num < this.data.form.factoryParams.length) {
					toast.setData({
						message: `请稍后(${num}/${this.data.form.factoryParams.length})`,
					});
				} else {
					clearTimeout(timer)
					// Toast.success('下发完成')
					Toast.clear()
					num = 0
					this.setData({
						issueResultBol: true,
						form: {
							command: undefined, //命令标识
							factoryParams: this.data.form.factoryParams,
							order: {} //命令内容 
						},
					})
					this.websocketClose()
				}

			})
			wx.onSocketError(function (res) {
				console.log('WebSocket连接出错！')
				Toast.fail('连接出错');
			})
		},
		websocketClose() {
			wx.closeSocket()
			wx.onSocketClose(function (res) {
				console.log('WebSocket连接已关闭！')
			})
		},

		// 显示屏
		// 下发节目
		program() {
			http.get({
				url: '/independent/screen-program/page',
				data: {},
				then: (res) => {
					console.log('节目列表', res);
					let list = res.data.data.list
					list = list.map(item => {
						if (item.programList && item.programList.length != 0) {
							if (item.programList[0].split('.')[item.programList[0].split('.').length - 1] == 'mp4') {
								item.urlType = 'mp4'
							} else {
								item.urlType = 'img'
							}
						} else {
							item.urlType = 'img'
						}
						return item
					})
					this.setData({
						programList: list,
					});
					this.start('program')
				}
			})
		},
		programIssue(event) {
			console.log(event.currentTarget.dataset.programid);
			let form = this.data.form
			form.command = 'commandXixunPlayer'
			form.programId = event.currentTarget.dataset.programid
			this.setData({
				form: form
			}, () => {
				this.websocketLink()
			})
		},
		programClose() {
			this.setData({
				programBol: false
			})
		},
		// 屏幕控制
		screenControl() {
			this.start('screenControl')
		},
		screenControlClose() {
			this.setData({
				screenControlBol: false
			})
		},
		btsTypeChange(event) {
			this.setData({
				btsType: event.detail,
			});
		},
		screenSwitchControl(event) {
			console.log(event.currentTarget.dataset.type);
			let type = event.currentTarget.dataset.type
			let form = this.data.form
			form.command = type == 2 ? 'reboot' : 'setScreenOpen'
			form.order.arg = type != 2 ? type : ''
			this.setData({
				form: form
			}, () => {
				this.websocketLink()
			})
		},
		screenBtsControl() {
			let form = this.data.form
			form.command = 'setBrightness'
			form.order.arg = this.data.screenBts
			this.setData({
				form: form
			}, () => {
				this.websocketLink()
			})
		},
		screenBtsChange(event) {
			this.setData({
				screenBts: event.detail
			}, () => {
				this.screenBtsControl()
			})
		},
		screenBtsChange1(event) {
			this.setData({
				screenBts: event.detail.value
			})
		},
		autoBtsIssue() {
			let form = this.data.form
			form.command = 'setAutoBrightness'
			form.order.sensitivity = this.data.sensitivity
			form.order.minBrightness = this.data.minBrightness
			this.setData({
				form: form
			}, () => {
				this.websocketLink()
			})
		},
		// 滚动文字
		subTitle() {
			this.start('subTitle')
		},
		// 截屏
		screenCapture() {
			let form = this.data.form
			form.command = 'screenshot'
			this.setData({
				form: form,
				screenFile: []
			}, () => {
				this.start('screenCapture')
			})
		},
		screenCaptureClose() {
			this.setData({
				screenCaptureBol: false
			})
		},
		// 下发结果
		issueResultClose() {
			this.setData({
				issueResultBol: false,
				issueResult: []
			})
		}
	}
})